package com.system_jsp.control;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.system_jsp.bean.UserBean;
import com.system_jsp.dao.UserDao;

/**
 * Servlet implementation class RegisterProcess
 */
@WebServlet(description = "用户注册处理", urlPatterns = { "/RegisterProcess" })
public class RegisterProcess extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		if (new UserDao().login(request.getParameter("username")
				.toString()) == null) { //检查用户是否存在
			UserBean ub = new UserBean();
			ub.setUsername(request.getParameter("username"));
			ub.setPasswd(request.getParameter("passwd"));
			ub.setGender(request.getParameter("gender"));
			ub.setBirth(request.getParameter("birth"));
			ub.setPhone(request.getParameter("phone"));
			ub.setAddress(request.getParameter("address"));

			int addrs = new UserDao().addUser(ub);
			
			if (addrs == 0) { //添加失败
				response.sendRedirect("./register.jsp?error=wrong");
				return;
			}
			
			request.getSession().setAttribute("username", ub.getUsername());
			response.sendRedirect("./regtolist.html");			
		} else { //用户名已存在
			response.sendRedirect("./register.jsp?error=userexist");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
